package llmserviceopenai

import io.ktor.server.application.*
import io.ktor.server.plugins.contentnegotiation.*
import io.ktor.serialization.kotlinx.json.*
import io.ktor.server.plugins.callloging.CallLogging
import io.ktor.server.routing.*
import io.ktor.util.AttributeKey

import llmserviceopenai.routes.chatRoutes
import llmserviceopenai.service.ChatService

import ragserverengine.milvus.MiluvsRoutes
import ragserverengine.neo4j.Neo4jRoutes

import llmserviceopenai.routes.embeddingRoutes
import llmserviceopenai.service.EmbeddingService

import llmserviceopenai.routes.rerankerRoutes
import llmserviceopenai.service.RerankService
import org.slf4j.event.Level

// 导入milvus客户端
import ragserverengine.milvus.core.MilvusClient
import ragserverengine.neo4j.core.Neo4jClient

fun Application.module() {

    install(ContentNegotiation) { json() }

    install(CallLogging) {
        level = Level.INFO
    }

    // 添加一个 MilvusClient 属性到applictaion中，用于全局使用
    val milvusKey = AttributeKey<MilvusClient>("MilvusClient")

    // 固定Url，后续使用配置文件进行管理
    val milvusClient = MilvusClient("http://10.10.1.167", 19530)

    milvusClient.connectV2()

    // 把MilvsuClient放到application中去，其它地方使用MilvusKey拿取
    this.attributes.put(milvusKey, milvusClient)

    // 应用关闭后自动断开连接
    environment.monitor.subscribe(ApplicationStopped) {
        milvusClient.cloasV2()
    }


    // ---------------  neo4j ---------------
    val neo4jKey = AttributeKey<Neo4jClient>("Neo4jClient")
    val neo4jClient = Neo4jClient()
    neo4jClient.conllect()

    this.attributes.put(neo4jKey, neo4jClient)

    environment.monitor.subscribe(ApplicationStopped) {
        neo4jClient.close()
        println("Neo4j connection closed")
    }


    val chatService = ChatService()
    val embeddingService = EmbeddingService()
    val rerankerService = RerankService()


    routing {
        chatRoutes(chatService)
        embeddingRoutes(embeddingService)
        rerankerRoutes(rerankerService)

        MiluvsRoutes()
        Neo4jRoutes()
    }
}

